<template>
  <view class="page">
    <view class="nav-style" :style="{'height':navHeight+'px','padding-top':statusBarHeight+'rpx'}">
      <image class="small-logo" src="/static/img/small-logo.png" mode="aspectFit"></image>
    </view>
    <div class="content" :style="{'padding-top':statusBarHeight+'rpx'}">
      <view class="welcome">欢迎使用艾瑞测！</view>
      <view class="sub-title">登录后更精彩，美好即将开始！</view>
      <view class="logo-wrap">
        <image class="logo" src="/static/img/device.png" mode="aspectFit" />
      </view>
      <!-- #ifdef APP-PLUS -->
      <button class="login" type="primary" @click="initLogin('quickLogin')">一键注册登录</button>
      <!-- #endif -->
      <view class="agree-wrap agree">
        <view style="display: flex;align-items: center;" @click="agreeChange">
          <image class="radio" :src="agree === '0' ? '/static/img/checkbox.png' : '/static/img/checkbox-active.png'" mode="aspectFit" />
          <text class="">同意</text>
        </view>
        <text class="link" @click="goAgreement">《用户协议》</text>与<text class="link" @click="goPrivacy">《隐私政策》</text>
      </view>
      <view class="login-btn" @click="goToLogin">账号密码登录</view>
    </div>
    <uni-popup
        ref="popup"
        type="bottom"
        class="popup-height"
        background-color="#fff"
    >
      <view class="register-popup">
        <view class="tips">
          温馨提示
        </view>
        <view class="allow-wrap">
          <view class="no-register">
            检测到您还未注册账号
          </view>
          <view class="allow">
            为了方便我们与您联系，请允许我们获取您的手机号码
          </view>
        </view>
        <view class="btn-wrap">
          <button class="phone-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" type="primary">授权电话号码</button>
        </view>
      </view>
    </uni-popup>
    <uni-popup
        ref="agreement"
        type="center"
        style="border-radius: 26rpx;"
    >
      <view class="agreement-height">
        <image class="agree-bg" src="/static/img/agree-box.png" mode="widthFix"></image>
        <view class="login-content">
          <rich-text :nodes="content"></rich-text>
          <view class="agreement-btn-wrap">
            <view class="refuse-btn" @click="onRefuse">拒绝</view>
            <view class="ok-btn" @click="onOk">同意并继续</view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getDictionaryByType, Shipment } from '@/utils/api.js'
import iosLightConfig from './ios-light-config.json'
import iosDarkConfig from './ios-dark-config.json'
import androidConfig from './config.json'
const platform = uni.getSystemInfoSync().platform
const ydLogin = uni.requireNativePlugin('YD-Login')
export default {
  name: 'Login',
  data() {
    return {
      saveBluetoothDevice_key:"saveBluetoothDevice",//保存到本地存储中的key
      authLoading: false,
      authPhoneLoading: false,
      showComplete: false,
      isNeedScan: false,
      agree: '0',
      content: '',
      navHeight: '',
      statusBarHeight: '',
      loginType: '',
      quickLogin: {
        step: 0,
        loginTip: '',
        token: '',
        accessToken: '',
      }
    }
  },
  onLoad(op) {
	  // console.log(ydLogin,'onload中打印');
    uni.removeStorageSync(this.saveBluetoothDevice_key)
    let {statusBarHeight,system} = uni.getSystemInfoSync()
    this.statusBarHeight = statusBarHeight
    this.navHeight = statusBarHeight + (system.indexOf('iOS') > -1 ? 44 : 48)
    this.getData(false)
    if (op.scan && op.scan === '1') {
      console.log(op)
      this.isNeedScan = true
    } else {
      this.isNeedScan = false
    }
  },
  methods: {
    async getData(tag) {
      if (tag) {
        uni.showLoading({
          title: 'loading'
        });
      }
      const res = await getDictionaryByType({ Type: 'UserAgreement' })
      if (res.Code === 200) {
        this.content = decodeURIComponent(res.Data[0].Value).replace(/\+style/g, ' style')
        if (tag) {
          uni.hideLoading()
        }
      }
    },
    open() {
      this.$refs.popup.open('top')
    },
    close() {
      this.$refs.popup.close()
    },
    appLogin() {
      uni.reLaunch({ url: '/pages/home/index' })
    },
    onScan() {
      uni.scanCode({
        onlyFromCamera: true,
        success: async (res) => {
          if (res.result && res.result.includes('mac_id')) {
            const params = res.result.split('?')[1]
            const mac_id = params.split('=')[1]
            const { Phone } = this.$store.state.vx_u_info
            try {
              const response = await Shipment({ Phone, mac_id })
              console.log(response)
              if (response.Code === 200) {
                uni.showToast({ title: '出货成功', icon: 'success' })
              } else {
                uni.showToast({ title: response.Message || '请稍后再尝试', icon: 'none' })
              }
              uni.navigateTo({
                url: '/pages/welcome/index'
              })
            } catch (e) {
              console.log(e)
            }
          } else {
            uni.showModal({
              title: '提示',
              content: '请扫描正确的二维码',
              success: (res) => {
                if (res.confirm) {
                  this.onScan()
                } else if (res.cancel) {
                  uni.navigateTo({
                    url: '/pages/welcome/index'
                  })
                }
              }
            })
          }
        }
      })
    },
    getUserInfo(e) {
      if (this.agree === '0') {
        uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' })
        return
      }
      this.authLoading = true
      console.log(e.userInfo || e.target.userInfo)
      this.$store.commit('$uStore', { name: 'vx_t_u_info', value: e.userInfo || e.target.userInfo })
      uni.login({
        provider: 'weixin',
        success: res => {
          console.log(res)
          if (res.code) {
            this.$store.dispatch('$dLogin', res.code).then(res => {
              if (res.type === false) {
                this.$refs.popup.open('bottom')
              } else if (res.type === true) {
                uni.reLaunch({ url: '/pages/home/index' })
              }
            })
          }
        }
      })
    },
    async getPhoneNumber(e) {
      let obj = e.detail || e
      if (obj.errMsg === 'getPhoneNumber:ok') {
        this.$store.dispatch('$dGetPhone', obj).then(data => {
          this.$store.dispatch('$dRegister', data).then(res => {
            if (res.type === false) {
              uni.showToast({ title: '注册失败~' })
            } else if (res.type === true) {
              uni.reLaunch({ url: '/pages/home/index' })
            }
          })
        })
      } else {
        uni.showToast({ title: '您拒绝了授权~,注册失败~' })
      }
    },
    onClose() {
      this.showComplete = false
      this.authLoading = false
    },
    async agreeChange() {
      console.log(this.agree)
      if (this.agree === '0') {
        if (!this.content) {
          await this.getData(true)
        } else {
          this.$refs.agreement.open('center')
        }
      }
    },
    goAgreement() {
      uni.navigateTo({ url: '/pages/agreement/index' })
    },
    goPrivacy() {
      uni.navigateTo({ url: '/pages/privacy/index' })
    },
    onOk() {
      this.$refs.agreement.close()
      this.agree = '1'
    },
    onRefuse() {
      this.$refs.agreement.close()
      this.agree = '0'
    },
    initLogin(loginType) {
      if (this.agree === '0') {
        uni.showModal({
          title: '提示',
          content: '请先同意用户协议和隐私政策',
          showCancel: false
        });
        return
      }
      this.loginType = loginType
      this[loginType].token = ''
      this[loginType].accessToken = ''
      // 初始化
      console.log(ydLogin,'ydLogin')
      ydLogin.registerWithBusinessID({
        // businessId: '2bcf39525f064645b242c37749db31d1',
        businessId: '8401f0c9368b446f957d8a674245d99a',
        loginType,
        timeout: 3000
      }, (data) => {
        console.log('registerWithBusinessID ', data)
        if (data.success) {
          this[loginType].loginTip = '初始化成功'
          this[loginType].step = 1
          this.verifyNumber()
        } else {
          this[loginType].loginTip = '初始化失败'
        }
      })
    },
    verifyNumber() {
      console.log('verifyNumber')
      const loginType = this.loginType
      if (this[loginType].step !== 1) {
        uni.showToast({
          icon: 'none',
          title: '请先初始化号码认证',
          duration: 800
        })
        return
      }
      // 自定义授权页视图
      let config = {}
      const uiTheme = plus.navigator.getUiStyle()
      console.log(uiTheme)
      if (platform === 'android') {
        config = androidConfig
      } else if (platform === 'ios' && uiTheme === 'dark') {
        config = iosDarkConfig
      } else if (platform === 'ios') {
        config = iosLightConfig
      }
      console.log(config)
      // 判断是否可以一键登录
      ydLogin.shouldQuickLogin((data) => {
        console.log('shouldQuickLogin', data)
        if (!data.success) {
          this[loginType].loginTip = '请检查网络，必须开启蜂窝流量，必须上网网卡为移动、电信、联通运营商'
          uni.showToast({
            title: '请开启蜂窝流量',
            icon: 'none',
            duration: 1500,
            mask: true
          });
          // uni.showModal({
          //   title: '提示',
          //   content: '请检查网络，必须开启蜂窝流量，必须上网网卡为移动、电信、联通运营商',
          //   showCancel: false
          // });
          return
        }
        // 预取号
        ydLogin.getPhoneNumberCompletion((data) => {
          console.log('getPhoneNumberCompletion ', data)
          if (!data.success) {
            this[loginType].loginTip = data.desc || '预取号失败'
            this[loginType].token = ''
            uni.showToast({
              icon: 'none',
              title: data.desc || '预取号失败',
              duration: 800
            })
            return
          }
          this[loginType].loginTip = ''
          this[loginType].token = data.token
          ydLogin.setCustomView(config, this.handleVerificationEvent)
          // 拉起授权页面
          ydLogin.cucmctAuthorizeLoginCompletion((data) => {
            console.log('cucmctAuthorizeLoginCompletion ', data)
            if (!data.success && !data.cancel) {
              this[loginType].loginTip = '授权失败'
              uni.showToast({
                icon: '',
                title: '授权失败',
                duration: 800
              })
              return
            } else if (data.cancel) {
              this[loginType].loginTip = '用户取消取号'
              uni.showToast({
                icon: '',
                title: '取消授权',
                duration: 800
              })
              return
            }
            uni.showToast({
              icon: '',
              title: '授权成功',
              duration: 800
            })
            this[loginType].loginTip = ''
            this[loginType].accessToken = data.accessToken
            // uni.showModal({
            //   title: '授权成功',
            //   content: `quickLogin ${JSON.stringify(this.quickLogin)}`,
            //   showCancel: false
            // })
            this.postToken()
            ydLogin.closeAuthController()
          })
        })
      })
    },
    // verifyInputNumber() {
    //   const loginType = this.loginType
    //   ydLogin.numberVerify(this.mobileNumber, (data) => {
    //     console.log('numberVerify callback: ', data)
    //     if (data && data.success) {
    //       this[loginType].token = data.token
    //       this[loginType].accessCode = data.accessCode
    //     } else {
    //       this[loginType].token = data.token
    //       this[loginType].accessCode = ''
    //       this[loginType].loginTip = data ? data.errorMsg : 'numberVerify 失败'
    //     }
    //   })
    // },
    handleVerificationEvent(data) {
      console.log('handleVerificationEvent ', data)
      let title = ''
      if (platform === 'ios') {
        // * iOS授权页生命周期action:
        // authViewDidLoad -- 加载授权页
        // authViewWillAppear -- 授权页已经出现
        // authViewWillDisappear -- 授权页将要消失
        // authViewDidDisappear -- 授权页已经消失
        // authViewDealloc -- 授权页销毁

        // * 页面默认组件点击事件action
        // loginAction -- 登录按钮点击事件（含checked: 0/1）
        // checkedAction -- 复选框事件（含checked: 0/1）
        // appDPrivacy -- 默认协议点击事件
        // appFPrivacy -- 第一个协议点击事件
        // appSPrivacy -- 第二个协议点击事件
        title = `action: ${data.action};checked: data.checked`
        // 关闭授权页
        if (['handleCustomEvent1', 'handleCustomEvent2', 'handleCustomEvent3'].includes(data.action)) {
          ydLogin.closeAuthController()
        }
      } else if (platform === 'android') {
        // * android授权页生命周期钩子：lifecycle
        // onCreate -- 页面创建
        // onStart -- 页面已开始活动
        // onResume -- 页面展示
        // onPause -- 页面非活动状态
        // onStop -- 页面已停止
        // onDestroy -- 页面销毁

        // * 页面默认组件点击事件: clickViewType
        // privacy -- 隐私协议点击事件
        // checkbox -- 复选框点击事件（含isCheckboxChecked: 0/1）
        // loginButton -- 登录按钮点击事件（含isCheckboxChecked: 0/1）
        // leftBackButton -- 左上角返回按钮点击事件
        if (data.viewId) {
          // 自定义组件事件
          title = `点击: ${data.viewId}`
        } else if (data.lifecycle) {
          title = `周期: ${data.lifecycle}`
        } else {
          title = '未知'
        }
      }
      console.log(data)
      // uni.showToast({
      // 	icon: '',
      // 	title: title,
      // 	duration: 800
      // })
    },
    async postToken() {
      const data = {
        accessToken: this.quickLogin.accessToken,
        token: this.quickLogin.token
      }
      // uni.showModal({
      //   title: '提示',
      //   content: `调取接口:App/Login => data = ${JSON.stringify(data)}`,
      //   showCancel: false
      // })
      this.$store.dispatch('$appLogin', data).then(res => {
        if (res.type === false) {
          uni.showModal({
            title: '错误',
            content: `接口:App/Login => response = ${JSON.stringify(res.payload)}`,
            showCancel: false
          })
        } else if (res.type === true) {
          if (this.isNeedScan) {
            this.onScan()
          } else {
            uni.reLaunch({ url: '/pages/home/index' })
          }
        }
      })
      // const res = await AppLogin(data)
      // if (res.Code === 200) {
      //   console.log(res.Data)
      //   uni.showToast({
      //     title: '验证成功',
      //     icon: 'success'
      //   })
      //   uni.reLaunch({ url: '/pages/home/index' })
      // } else {
      //   uni.showToast({
      //     title: JSON.stringify(res),
      //     icon: 'none'
      //   })
      //   uni.showModal({
      //     title: '错误',
      //     content: `接口:App/Login => response = ${JSON.stringify(data)}`,
      //     showCancel: false
      //   })
      // }
    },
    goToLogin() {
      uni.navigateTo({ url: '/pages/password-login/index' })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
  background-color: #ffffff;
  .nav-style {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1000;
    display: flex;
    padding-left: 23rpx;
    align-items: center;
    background-color: #ffffff;
    .small-logo {
      width: 100rpx;
      height: 35rpx;
    }
  }
  .content {
    margin-top: 203rpx;
    padding: 0 64rpx;
  }
  .welcome {
    margin-top: 100rpx;
    font-size: 46rpx;
    font-weight: bold;
    color: #323232;
    line-height: 46rpx;
  }
  .sub-title {
    margin-top: 30rpx;
    font-size: 27rpx;
    color: #666666;
    line-height: 60rpx;
  }
  .logo-wrap {
    width: 436rpx;
    height: 168rpx;
    margin: 163rpx auto 0;
    .logo {
      width: 436rpx;
      height: 168rpx;
    }
  }
  .login {
    margin-top: 182rpx;
    margin-bottom: 30rpx;
    width: 465rpx;
    height: 85rpx;
    background: #1E64E1;
    border-radius: 15rpx;
  }
  .login-btn {
    position: absolute;
    bottom: 100rpx;
    left: 0;
    right: 0;
    margin: auto;
    text-align: center;
    //border-radius: 46rpx;
    color: #333333;
    //border: 1rpx solid #aaaaaa;
  }
  .agree {
    color: #A7A6A6;
    font-size: 27rpx;
    font-weight: 400;
    .link {
      color: #2955CC
    }
  }
}
.popup-height {
  height: 40vh;
}
.register-popup {
  height: 40vh;
  padding: 30rpx;
  .tips {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
  .btn-wrap {
    margin: 30rpx auto;
    display: flex;
    justify-content: center;
  }
  .phone-btn {
    margin-top: 50rpx;
  }
  .no-register {
    font-size: 28rpx;
    color: #3b4144;
  }
  .allow-wrap {
    margin-top: 60rpx;
    text-align: center;
  }
  .allow {
    font-size: 28rpx;
    margin-top: 20rpx;
    color: #909399;
  }
}
.agree-wrap {
  width: 470rpx;
  margin: 50rpx auto 0;
  display: flex;
  align-items: center;
  .radio {
    width: 27rpx;
    height: 27rpx;
    margin-right: 10rpx;
  }
}
.agreement-height {
  width: 615rpx;
  height: 70vh;
  margin: 0 auto;
  border-radius: 26rpx;
  background-color: #ffffff;
  position: relative;
  .agree-bg {
    width: 615rpx;
    position: absolute;
    z-index: 0;
  }
  .login-content {
    width: 515rpx;
    position: absolute;
    padding: 60rpx 50rpx 0;
    height: calc(100% - 100rpx);
    overflow-y: scroll;
    color: #000000;
  }
  .agreement-btn-wrap {
    background-color: #ffffff;
    padding-top: 20rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .ok-btn {
      width: 250rpx;
      height: 85rpx;
      line-height: 85rpx;
      background: #1E64E1;
      border-radius: 15rpx;
      text-align: center;
      font-size: 31rpx;
      font-weight: 400;
      color: #FFFFFF;
    }
    .refuse-btn {
      width: 250rpx;
      height: 85rpx;
      line-height: 85rpx;
      font-size: 31rpx;
      font-weight: 400;
      color: #333333;
      background: #EBEBED;
      text-align: center;
      border-radius: 15rpx;
    }
  }
}
//@media (prefers-color-scheme: dark){
//  .content {
//    .welcome {
//      color: white;
//    }
//    .sub-title {
//      color: #999999;
//    }
//  }
//  .agreement-height {
//    background-color: #1B1C1E;
//    color: white;
//    .agree-bg {
//      display: none;
//    }
//    .agreement-btn-wrap {
//      background-color: #1B1C1E;
//    }
//  }
//}
</style>
